package com.edocbase.desktopserver.impl.jetty;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.edocbase.desktopserver.ActionMapper;
import com.edocbase.desktopserver.DesktopServerActivator;
import com.edocbase.desktopserver.impl.ActionExecutor;
import com.edocbase.desktopserver.impl.ActionMapping;

public class ActionFilter implements Filter {
	
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest r, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)r;
		String uri = request.getRequestURI();
		if (uri.endsWith(".do")){
			DesktopHttpRequest desktopRequest = new DesktopHttpRequest(request);
			ActionMapper mapper = DesktopServerActivator.getActivator().getActionMapper();
			ActionMapping mapping = mapper.getActionMapping(desktopRequest);
			ActionExecutor executor = new ActionExecutor();
			try {
				Object obj = executor.execute(mapper, mapping, desktopRequest,new DesktopHttpResponse((HttpServletResponse)resp));
				if (obj != null){
					String path = obj.toString();
					request.getRequestDispatcher(path).forward(request, resp);
					return;
				}else{
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		chain.doFilter(request, resp);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
